package cn.hy.考试;

import java.util.Arrays;

/**
 * 给你一个长度为n的无序数组，找到其中第k小的数。
 */
public class Test03 {


    public static void main(String[] args) {

        int[] arr = new int[]{2, 5, 3, 9, 7};
        quickSort(arr, 0, arr.length - 1);
        //bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
        int k = 3;
        System.out.println(arr[k - 1]);
    }

    public static void bubbleSort(int[] arr) {
        if (arr == null || arr.length == 0) {
            return;
        }
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j + 1);
                }
            }
        }
    }

    public static void quickSort(int[] arr, int l, int r) {
        if (l >= r) {
            return;
        }
        int p = partition(arr, l, r);
        quickSort(arr, l, p - 1);
        quickSort(arr, p + 1, r);
    }

    private static int partition(int[] arr, int l, int r) {
        int small = l;
        for (int i = l; i < r; i++) {
            if (arr[i] < arr[r]) {
                swap(arr, i, small++);
            }
        }
        swap(arr, r, small);
        return small;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
